<template>
  <div class="class-manage">
    <div class="header">
      <div class="search">
        <span>用户信息：</span>
        <el-input
          v-model="stuName"
          placeholder="请输入用户名称"
          size="large"
          style="width: 240px"
        >
        </el-input>
        <el-button class="search-btn" @click="search()">搜索</el-button>
      </div>
      <div class="btns" v-if="classuserId != undefined">
        <el-button @click="addStudent()">添加</el-button>
        <el-button @click="batchDelete()">批量删除</el-button>
        <el-button @click="batchImport()">批量导入</el-button>
      </div>
    </div>
    <!-- 导入学生 -->
    <!-- <div class="export-btn">
      <span>导入学生：</span>
      <el-button text type="primary" @click="importStudent()">Excel导入<i class="iconfont icon-daoru1"></i></el-button>
      <el-button text type="primary" @click="importHistoryClass()">历史班级导入<i class="iconfont icon-daoru1"></i></el-button>
    </div> -->
    <!-- 表格 -->
    <div class="chapter-list">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        empty-text="暂无数据"
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column property="name" label="学生姓名" width="200" />
        <el-table-column property="userNumber" label="学号" width="200" />
        <el-table-column
          :formatter="sexFormatter"
          property="sex"
          label="性别"
          width="150"
        />
        <el-table-column
          property="telephoneNumber"
          label="联系方式"
          width="200"
        />
        <el-table-column property="email" label="邮箱" width="200" />
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button
              v-if="classuserId != undefined"
              size="small"
              text
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              style="color: #457aff"
            >
              修改
            </el-button>
            <el-button
              v-if="classuserId != undefined"
              size="small"
              text
              type="primary"
              @click="resetPassword(scope.$index, scope.row)"
              style="color: #457aff"
            >
              初始密码
            </el-button>
            <!-- <el-button size="small" text type="primary" @click="handleEnd(scope.$index, scope.row)" style="color: #457AFF;">
              结课
            </el-button>
            <el-button
              style="margin-left: 0px;color: #457AFF;"
              text
              type="primary"
              size="small"
              @click="handleManage(scope.$index, scope.row)"
            >
              管理学生
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="tableData.length > 0"
        class="my_pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加学生弹窗 -->
    <el-dialog
      class="add-dialog"
      :close-on-click-modal="false"
      v-model="addDialogVisiable"
      width="750px"
      @close="closeAddDialog()"
      center
    >
      <div class="dialog-body">
        <el-form
          ref="addform"
          :inline="true"
          :model="addform"
          :rules="rules"
          label-width="90px"
        >
          <el-form-item label="学号 :" prop="userNumber">
            <el-input
              :disabled="isEdit"
              v-model="addform.userNumber"
              placeholder="请输入学号"
              @input="debouncedCheckUserNumber"
            ></el-input>
          </el-form-item>
          <el-form-item label="学生名称 :" prop="name">
            <el-input
              v-model="addform.name"
              maxlength="10"
              placeholder="请输入学生名称"
              :disabled="checkDisabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系方式 :" prop="telephoneNumber">
            <el-input
              v-model="addform.telephoneNumber"
              maxlength="11"
              placeholder="请输入联系方式"
              :disabled="checkDisabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱 :" prop="email">
            <el-input
              v-model="addform.email"
              maxlength="50"
              placeholder="请输入邮箱"
              :disabled="checkDisabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别 :" prop="sex" style="width: 100%">
            <el-radio-group
              v-model="addform.sex"
              placeholder="请选择性别"
              :disabled="checkDisabled"
            >
              <el-radio :value="1">男</el-radio>
              <el-radio :value="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" @click="submitForm()">保 存</el-button>
      </template>
    </el-dialog>

    <!-- 批量导入 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogExcel"
      width="500px"
      @close="dialogExcel = false"
      center
    >
      <div class="dialog-body">
        <div>
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleRemove"
            :limit="1"
            :show-file-list="false"
            accept=".xlsx,.xls"
          >
            <el-button round>上传Excel</el-button>
          </el-upload>
          <span
            @click="downloadTemplate"
            style="cursor: pointer; color: #457aff; text-decoration: none"
            >学生信息模板.xls
            <i class="iconfont icon-tubiaozhizuo-"></i>
          </span>
        </div>
        <!-- 显示上传的文件名 -->
        <div v-if="uploadedFileName" class="uploaded-file">
          <span>{{ uploadedFileName }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="background-color: #457aff"
            type="primary"
            @click="confirmImport()"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from "lodash";

export default {
  data() {
    return {
      classId: "",
      stuName: "",
      currentPage: 1,
      pageSize: 10,
      addDialogVisiable: false,
      addform: {
        email: "",
        name: "",
        userNumber: "",
        telephoneNumber: "",
        sex: 1,
      },
      isEdit: false,
      checkDisabled: false,
      editId: "",
      rules: {
        name: [{ required: true, message: "请输入学生名称", trigger: "blur" }],
        userNumber: [
          { required: true, message: "请输入学号", trigger: "blur" },
        ],
      },
      tableData: [],
      totalCount: "",
      classuserId: "",
      multipleSelection: [],
      dialogExcel: false,
      uploadedFile: null,
      uploadedFileName: "",
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.classId = this.$route.query.classId;
    this.getTableData();

    // 创建防抖的学号检查方法
    this.debouncedCheckUserNumber = debounce(this.checkUserNumber, 500);
  },
  methods: {
    // 搜索
    search() {
      this.currentPage = 1;
      this.getTableData();
    },
    // 获取列表数据
    getTableData() {
      this.$axios
        .get(
          `/tes/course/class/${this.classId}/student/page?pageNum=${this.currentPage}&pageSize=${this.pageSize}&userInfo=${this.stuName}`
        )
        .then((res) => {
          this.tableData = res.data.content;
          this.totalCount = res.data.total;
        });
      this.$axios
        .get("/tes/course/class/" + this.classId + "/flag")
        .then((res) => {
          this.classuserId = res.data;
        });
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.getTableData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableData();
    },
    handleEdit(index, row) {
      console.log(row, 666);

      this.isEdit = true;
      this.checkDisabled = false;
      this.editId = row.id;
      this.addform = {
        email: row.email,
        name: row.name,
        userNumber: row.userNumber,
        telephoneNumber: row.telephoneNumber,
        sex: row.sex,
      };
      this.addDialogVisiable = true;
    },

    closeAddDialog() {
      this.addDialogVisiable = false;
      this.$refs.addform.resetFields();
    },
    sexFormatter(row) {
      return row.sex == 1 ? "男" : "女";
    },

    // 处理文件变化
    handleFileChange(file) {
      console.log(file, 666);
      this.uploadedFile = file.raw;
      this.uploadedFileName = file.name;
      console.log("上传的文件:", file.name);
    },
    handleRemove(file) {
      this.uploadedFile = null;
      this.uploadedFileName = "";
      console.log("移除文件:", file.name);
    },

    // 下载学生信息模板
    downloadTemplate() {
      const loading = this.$loading({
        lock: true,
        text: "下载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      this.$axios({
        method: "get",
        url: "/tes/user/model/download/student",
        responseType: "blob",
      })
        .then((response) => {
          // 创建blob对象
          const blob = new Blob([response.data], {
            type: "application/vnd.ms-excel",
          });

          // 创建下载链接
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = url;
          link.download = "学生信息模板.xls"; // 确保文件名有正确的扩展名

          // 触发下载
          document.body.appendChild(link);
          link.click();

          // 清理
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          this.$message.success("下载成功");
        })
        .catch((error) => {
          this.$message.error("下载失败");
          console.error("下载错误:", error);
        })
        .finally(() => {
          loading.close();
        });
    },

    // 确认导入
    confirmImport() {
      if (!this.uploadedFile) {
        this.$message.error("请上传文件");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const formData = new FormData();
      formData.append("file", this.uploadedFile);
      this.$axios
        .post(
          `/tes/course/${this.courseId}/class/${this.classId}/student/model-import?errorFlag=true`,
          formData
        )
        .then((res) => {
          this.getTableData();
          this.$message.success("导入成功");
          this.dialogExcel = false;
        });
      this.$refs.uploadRef.clearFiles();
      loading.close();
    },

    // 添加学生
    addStudent() {
      this.addDialogVisiable = true;
      this.isEdit = false;
      this.checkDisabled = false;
      this.addform = {
        email: "",
        name: "",
        userNumber: "",
        telephoneNumber: "",
        sex: 1,
      };
      this.$nextTick(() => {
        this.$refs.addform.resetFields();
      });
    },

    // 保存学生
    submitForm() {
      if (!this.isEdit) {
        this.$refs.addform.validate((valid) => {
          if (valid) {
            this.$axios
              .post(
                `/tes/course/${this.courseId}/class/${this.classId}/student?errorFlag=`,
                this.addform
              )
              .then((res) => {
                this.getTableData();
                this.addDialogVisiable = false;
                this.$message.success("添加成功");
              });
          }
        });
      } else {
        this.$axios
          .put(`/tes/user/${this.editId}?identity=2`, this.addform)
          .then((res) => {
            this.getTableData();
            this.addDialogVisiable = false;
            this.$message.success("修改成功");
          });
      }
    },

    // 批量导入
    batchImport() {
      this.dialogExcel = true;
    },

    // 批量删除
    batchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择要删除的学生");
        return;
      }
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .post(
            `/tes/course/${this.courseId}/class/${this.classId}/student/batch-delete?errorFlag=true`,
            this.multipleSelection
          )
          .then((res) => {
            this.getTableData();
            this.$message.success("删除成功");
          });
      });
    },

    // 初始密码
    resetPassword(index, row) {
      this.$axios.put(`/tes/user/${row.id}/init-password`).then((res) => {
        this.$message.success("初始密码成功");
      });
    },

    // 检查学号是否存在
    checkUserNumber() {
      this.$axios
        .post(`/tes/user/student/info?identity=2`, {
          userNumber: this.addform.userNumber,
        })
        .then((res) => {
          if (res.code == "200") {
            if (res.data) {
              this.addform.name = res.data.name;
              this.addform.telephoneNumber = res.data.telephoneNumber;
              this.addform.email = res.data.email;
              if (typeof res.data.sex == undefined) {
                this.addform.sex = 1;
              } else {
                this.addform.sex = res.data.sex;
              }
              this.$message({
                message: "自动填充已存在的学生",
                type: "warning",
              });
              this.checkDisabled = true;
            } else {
              this.addform.telephoneNumber = "";
              this.addform.email = "";
              this.addform.name = "";
              this.checkDisabled = false;
            }
          } else {
            this.$message.error(res.message);
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.class-manage {
  background-color: #fff;
  padding: 10px 40px 40px 80px;
  box-sizing: border-box;
  min-height: 550px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .search {
      display: flex;
      align-items: center;
      gap: 10px;
      span {
        font-size: 16px;
        color: #252e54;
      }
      .search-btn {
        height: 40px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #a5beff;
        color: #457aff;
        line-height: 40px;
      }
    }
    .btns {
      display: flex;
      align-items: center;
      .el-button {
        background: #457aff;
        border-radius: 4px;
        color: #fff;
      }
    }
  }
  .export-btn {
    display: flex;
    align-items: center;
    margin-top: 20px;
    span {
      font-size: 16px;
      color: #252e54;
    }
    .el-button {
      margin-left: 0;
      color: #457aff;
      &:hover {
        background-color: #fff;
      }
      i {
        font-size: 16px;
        margin-left: 5px;
      }
    }
  }
  .chapter-list {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 20px;
    .my_pagination {
      :deep(.el-pager li.is-active) {
        color: #457aff;
      }
      :deep(.el-pager li:hover) {
        color: #457aff;
      }
    }
  }

  .add-dialog {
    padding: 40px 0;
    .el-button {
      background: #457aff;
      border-radius: 4px;
      color: #fff;
    }
  }

  .dialog-body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
    > div {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    .el-button {
      color: #457aff;
      border: 1px solid #457aff;
      margin-right: 10px;
      &:hover {
        background-color: #457aff;
        color: #fff;
      }
    }
    .uploaded-file {
      margin-top: 15px;
      span {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }
    }
  }
}
</style>